<?php
/*
 * @Author: lokei
 * @Date: 2023-05-26 11:28:37
 * @LastEditors: lokei
 * @LastEditTime: 2023-06-28 09:49:51
 * @Description: 
 */
namespace App\Http\Controllers\Platform\Log;

use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use App\Models\Platform\Log\LogModel;
use Illuminate\Http\Request;

class LogController extends Controller {
    public function loginSuccess(Request $request) {
        $log = new LogModel();
        $log->ipAddress = $this->getRealIp();
        $log->operation = ($request->input('username') ? $request->input('username') . ':' : '') . '用户登入';
        $log->createtime = date('Y-m-d H:i:s', time());
        $log->save();
        return ResultTool::success();
    }

    function getRealIp()
	{
		
		$ip = data_get($_SERVER, 'HTTP_X_FORWARDED_FOR'); #获取用户ip
		if (strstr($ip, ",")) {#如果经过代理有多个ip,循环处理
			$ip_arr = explode(',', $ip);
			foreach ($ip_arr as $ip) {
				$ipint = sprintf('%u', ip2long($ip));#ip2long — 将 IPV4 的字符串互联网协议转换成长整型数字
				if ($ipint >= 0 && $ipint <= 50331647 || // {"0.0.0.0","2.255.255.255"},
					$ipint >= 167772160 && $ipint <= 184549375 || // {"10.0.0.0","10.255.255.255"},
					$ipint >= 2130706432 && $ipint <= 2147483647 || // {"127.0.0.0","127.255.255.255"},
					$ipint >= 2851995648 && $ipint <= 2852061183 || // {"169.254.0.0","169.254.255.255"}
					$ipint >= 2886729728 && $ipint <= 2887778303 || // {"172.16.0.0","172.31.255.255"},
					$ipint >= 3221225984 && $ipint <= 3221226239 || // {"192.0.2.0","192.0.2.255"},
					$ipint >= 3232235520 && $ipint <= 3232301055 || // {"192.168.0.0","192.168.255.255"},
					$ipint >= 4294967040 && $ipint <= 4294967295 // {"255.255.255.0","255.255.255.255"}
					){
						continue;
					}else{
						   break;
					}
					
					
						
			}
		}
		if($ip != '') {
			return trim($ip);
		} else {
			return request()->ip();
		}
	}

	public function list(Request $request) {
		$items = LogModel::orderBy('createtime', 'desc')->limit($request->input('limit'))->offset((intval($request->input('page')) - 1) * intval($request->input('limit')))->get();
		$res = ResultTool::success();
		$res['data']['items'] = $items;
		$res['data']['total'] = LogModel::count();
		return $res;
	}
}